package fi.hell.pollit.util

import fi.hell.util.mail.Mailer
import javax.mail.MessagingException
import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH

/**
 * Simple service for sending emails.
 *
 * Work is planned in the Grails roadmap to implement first-class email
 * support, so there's no point in making this code any more sophisticated.
 *
 * @author Jukka
 */
class MailerService {
    boolean transactional = false

    /**
     * Send email
     * @param String From email address that is shown as sender
     * @params List Recipient(s) in a list
     * @param String subject of this mail
     * @param String message text
     * @param String inReplyTo header info
     * @param Map attachments
     *
     */
    def sendEmail(def settings) throws MessagingException {
        def host = CH.config.mailer.host
        def port = CH.config.mailer.port
        Mailer mailer = new Mailer(host, port)

        if (settings.from) {
            mailer.setFrom(settings.from)
        } else {
            mailer.setFrom(CH.config.mailer.from)
        }

        def to = (settings.to instanceof String) ? [settings.to] : settings.to
        mailer.setRecipients(to)
        mailer.setSubject(settings.subject)
        mailer.setMessageText(settings.plainTextMessage)
        mailer.setHtmlMessage(settings.htmlMessage)
        if(settings.attachments) {
            mailer.setAttachments(settings.attachments)
        }
        def success = mailer.sendMail(settings.inReplyTo)
        return success
    }
}